import React, { useState, useEffect } from "react";
import {
  View,
  Keyboard,
  Alert,
  Text,
  TextInput,
  StyleSheet,
} from "react-native";
import { LoginPropsType } from "@/types/login";
import { router } from "expo-router";
import { useTheme } from "@/contexts/ThemeContext";

// 导入通用组件
import FormInput from "../components/FormInput";
import FormButton from "../components/FormButton";
import AgreementCheck from "../components/AgreementCheck";
import LoginContainer from "../components/LoginContainer";

// 导入自定义hooks
import { useLogin } from "@/hooks/Login/login-hook";
import {
  useFormValidation,
  validateEmail,
  validateCode,
} from "@/hooks/Login/validate-hook";

// 常量配置
const CODE_LENGTH = 6;
const COUNTDOWN_DURATION = 60;

const EmailLoginScreen: React.FC<LoginPropsType> = ({ showAlert }) => {
  // 状态管理
  const [email, setEmail] = useState("");
  const [code, setCode] = useState("");
  const [agreed, setAgreed] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const { colors } = useTheme();

  // 使用自定义hooks
  const { errors, validateField } = useFormValidation();
  const { isLoading, loginWithEmailCode, sendEmailCode , getLastLoginCredentials } = useLogin();

  // 组件挂载时初始化登录信息
  useEffect(() => initLoginCredentials() ,[]);

  // 倒计时管理
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown((prev) => (prev > 0 ? prev - 1 : 0));
      }, 1000);
    }
    return () => timer && clearInterval(timer);
  }, [countdown]);


  // 初始化登录凭据
  const initLoginCredentials = () => {
    const {email} = getLastLoginCredentials()
    // 设置默认值
    setEmail(email);
  }

  // 邮箱输入处理
  const handleEmailChange = (text: string) => {
    setEmail(text);
    if (errors.email) validateField("email", text, validateEmail);
  };

  // 验证码输入处理
  const handleCodeChange = (text: string) => {
    if (text.length <= CODE_LENGTH) {
      setCode(text);
      if (errors.code) validateField("code", text, validateCode, CODE_LENGTH);
    }
  };

  // 发送验证码
  const handleSendCode = async () => {
    Keyboard.dismiss();
    if (!validateField("email", email, validateEmail)) return;

    const result = await sendEmailCode(email);
    if (result.success) {
      showAlert("success", result.message);
      setCountdown(COUNTDOWN_DURATION);
    } else {
      showAlert("error", `发送失败: ${result.message}`);
    }
  };

  // 登录处理
  const handleLogin = async () => {
    Keyboard.dismiss();

    const isEmailValid = validateField("email", email, validateEmail);
    const isCodeValid = validateField("code", code, validateCode, CODE_LENGTH);
    if (!isEmailValid || !isCodeValid) return;

    if (!agreed) {
      Alert.alert("提示", "继续登录表示已阅读并同意用户协议", [
        { text: "取消", style: "cancel" },
        {
          text: "确定",
          onPress: async () => {
            setAgreed(true);
            await toLogin();
          },
        },
      ]);
      return;
    }
    await toLogin();
  };

  const toLogin = async () => {
    const result = await loginWithEmailCode(email, code);

    if (result.success) {
      showAlert("success", "登录成功");
      router.replace("/");
    } else {
      showAlert("error", `登陆失败:${result.message}`);
    }
  };

  const styles = StyleSheet.create({
    codeInput: {
      height: 48,
      borderWidth: 1,
      borderRadius: 8,
      paddingHorizontal: 16,
      fontSize: 16,
      color: colors.text.primary,
      backgroundColor: colors.inputBackground,
    },
    errorText: {
      marginTop: 4,
      color: colors.status.error,
      fontSize: 12,
    },
    codeInputContainer: {
      marginBottom: 24,
    },
    inputRow: {
      flexDirection: "row",
      alignItems: "flex-start",
      gap: 12,
    },
    inputWrapper: {
      flex: 1,
    },
    buttonWrapper: {
      width: 120,
      height: 48,
    },
  });

  const renderCodeInput = () => {
    return (
      <View style={styles.codeInputContainer}>
        <View style={styles.inputRow}>
          <View style={styles.inputWrapper}>
            <TextInput
              style={[
                styles.codeInput,
                {
                  borderColor: errors.code
                    ? colors.status.error
                    : colors.border.medium,
                },
              ]}
              placeholder="请输入验证码"
              placeholderTextColor={colors.text.hint}
              keyboardType="numeric"
              autoCapitalize="none"
              autoCorrect={false}
              value={code}
              onChangeText={handleCodeChange}
              onBlur={() =>
                validateField("code", code, validateCode, CODE_LENGTH)
              }
            />
          </View>
          <FormButton
            title={countdown > 0 ? `${countdown}s` : "获取验证码"}
            onPress={handleSendCode}
            disabled={countdown > 0}
            isLoading={isLoading && countdown === 0}
            style={styles.buttonWrapper}
          />
        </View>
        {errors.code && <Text style={styles.errorText}>{errors.code}</Text>}
      </View>
    );
  };

  return (
    <LoginContainer title="邮箱验证码登录" subtitle="使用邮箱验证码登录">
      <FormInput
        value={email}
        onChangeText={handleEmailChange}
        placeholder="请输入注册邮箱"
        keyboardType="email-address"
        error={errors.email}
        onBlur={() => validateField("email", email, validateEmail)}
      />
      {renderCodeInput()}
      <AgreementCheck agreed={agreed} setAgreed={setAgreed} />
      <FormButton
        title="登录"
        onPress={handleLogin}
        isLoading={isLoading && countdown > 0}
      />
    </LoginContainer>
  );
};

export default EmailLoginScreen;
